﻿/**************************************************************
 *
 * 唯一标识：0a4e601c-39a0-417c-a712-98eb286471de
 * 命名空间：Xunit.Sgr.Cap.HelperClass
 * 创建时间：2024/7/22 17:33:00
 * 机器名称：DESKTOP-HJ4OAG9
 * 创建者：CocoYuan
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 *
 **************************************************************/

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;

namespace Xunit.Sgr.Cap.HelperClass
{
    public static class ObservableMessageExtensions
    {
        public static async Task WaitOneMessage(this ObservableMessage observableMessage, string message, CancellationToken cancellationToken = default)
        {
            await WaitForMessages(observableMessage,
                (x) => { return x.Equals(message); },
                cancellationToken);
        }

        public static async Task WaitForMessages(this ObservableMessage observableMessage,
            Func<string, bool> comparison,
            CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            var cts = new CancellationTokenSource();
            cancellationToken.Register(() => cts.Cancel());

            await Task.Run(async () =>
            {
                void ObservableMessage_NotifyMessageChanged(object? sender, string message)
                {
                    if (comparison(message))
                    {
                        cts.Cancel();
                    }
                }

                observableMessage.NotifyMessageChanged += ObservableMessage_NotifyMessageChanged;

                try
                {
                    await Task.Delay(-1, cts.Token);
                }
                catch (TaskCanceledException)
                {
                }
                finally
                {
                    observableMessage.NotifyMessageChanged -= ObservableMessage_NotifyMessageChanged;
                }

                cancellationToken.ThrowIfCancellationRequested();
            }, cancellationToken);
        }
    }
}